<template>
  <div
    class="top-bar"
    :class="{ 'top-bar-scroll-background': isShowTopbarScrollBackground }"
  >
    <div class="center-wrapper">
      <div class="t-b-left">
        <ul>
          <li><img class="logo" :src="images.left_logo" alt="logo" /></li>

          <li
            :class="{ 'active-li': currentIndex === index }"
            v-for="(item, index) in titles"
            :key="index"
            @click="changeTitle(index, item)"
          >
            {{ item.name }}
          </li>

          <li @click="gotoPage('QA')">Q&A</li>
        </ul>
      </div>

      <div class="t-b-right">
        <img
          class="right-icon"
          :src="images.right_icon1"
          @click="gotoPage('Twitter')"
        />
        <img
          class="right-icon"
          :src="images.right_icon2"
          @click="gotoPage('Discord')"
        />
        <img
          id="topBtnAccount"
          class="right-icon"
          :src="images.right_icon3"
          @click="comming"
        />
      </div>
    </div>

    <div class="mobile">
      <div class="t-b-left">
        <img class="logo" :src="images.m_left_logo" alt="logo" />
      </div>

      <div class="t-b-right">
        <img
          class="right-icon"
          :src="images.m_right_icon1"
          @click="gotoPage('Twitter')"
        />
        <img
          class="right-icon"
          :src="images.m_right_icon2"
          @click="gotoPage('Discord')"
        />
        <img
          id="m_topBtnAccount"
          class="right-icon"
          :src="images.m_right_icon3"
          @click="comming"
        />
      </div>
    </div>
  </div>
</template>

<script>
import MetaMask from "@/utils/metamask.js";
import { setCookie, clearCookies, getCookie } from "@/utils/cookie";
import MetaMaskOnboarding from "@metamask/onboarding";
import { isPhone } from "../utils";
const currentUrl = new URL(window.location.href);
const forwarderOrigin =
  currentUrl.hostname === "localhost" ? "http://localhost:9010" : undefined;

export default {
  name: "TopBar",
  data() {
    return {
      // static
      images: {
        left_logo: require("@/assets/images/topbar/topbar_logo.png"),
        right_icon1: require("@/assets/images/topbar/topbar_right_icon1.png"),
        right_icon2: require("@/assets/images/topbar/topbar_right_icon2.png"),
        right_icon3: require("@/assets/images/topbar/topbar_right_icon3.png"),
        m_left_logo: require("@/assets/images/topbar/m_topbar_logo.png"),
        m_right_icon1: require("@/assets/images/topbar/m_topbar_right_icon1.png"),
        m_right_icon2: require("@/assets/images/topbar/m_topbar_right_icon2.png"),
        m_right_icon3: require("@/assets/images/topbar/m_topbar_right_icon3.png"),
      },
      // titles
      titles: [
        { id: "home", name: "HOME" },
        { id: "story", name: "STORY" },
        { id: "character", name: "CHARACTER" },
        { id: "about", name: "ABOUT" },
        { id: "roadmap", name: "ROADMAP" },
      ],
      // active
      currentIndex: 0,
      // flag
      isShowTopbarScrollBackground: false,
      // account
      account: "",
    };
  },
  methods: {
    // ========== async ==========
    async getNonce(address) {
      this.isConnect = true;
      let top = address.slice(0, 4);
      let bottom = address.substring(address.length - 4, address.length);
      this.account = top + "...." + bottom;
      this.canContented = false;
      localStorage.setItem("isLogin", JSON.stringify(true));
      setCookie("token", address);
      setCookie("publicAddress", address);
      // let count = await MetaMask.getGmsNFTBlanace();
      // if (count > 0) {
      //   localStorage.setItem("isMember", JSON.stringify(true));
      // }
    },
    async linkMetaMask() {
      // const newAccounts = await ethereum.request({
      //   method: "eth_requestAccounts",
      // });
    },
    async initialize() {
      let that = this;
      let onboardButton = document.getElementById("topBtnAccount");
      if (isPhone()) {
        onboardButton = document.getElementById("m_topBtnAccount");
      }
      let state = await MetaMask.init();
      if (state === 0) {
        onboardButton.addEventListener("click", () => {
          that.canContented = false;
          const onboarding = new MetaMaskOnboarding({ forwarderOrigin });
          onboarding.startOnboarding();
          onboardButton.disabled = true;
        });
      } else if (state === 1) {
        this.getAccount();
        onboardButton.addEventListener("click", () => {
          MetaMask.connect()
            .then((res) => {
              console.log(res);
              that.getNonce(res[0]);
            })
            .catch((err) => {
              console.log(err);
            });
        });
      }
    },
    async getAccount() {
      let that = this;
      ethereum.on("accountsChanged", function (accounts) {
        if (accounts && accounts.length > 0) {
          that.getNonce(accounts[0]);
        } else {
          that.isConnect = false;
          clearCookies();
          localStorage.clear();
        }
      });
    },
    checkLogin() {
      let publicAddress = getCookie("publicAddress");
      if (publicAddress) {
        this.getNonce(publicAddress);
      }
    },
    getUserInfo() {
      this.initialize();
      this.checkLogin();
    },
    // ========== common fn ==========
    // change title index
    changeTitle(index, item) {
      this.currentIndex = index;
      document.getElementById(item.id).scrollIntoView({ behavior: "smooth" });
      // window.scrollTo(0, document.getElementById(item.id).offsetTop);
    },
    // scroll listener
    handleScroll() {
      let scroll =
        document.documentElement.scrollTop || document.body.scrollTop;
      let storyTop = document.getElementById("story").offsetTop;
      let characterTop = document.getElementById("character").offsetTop;
      let aboutTop = document.getElementById("about").offsetTop;
      let roadmapTop = document.getElementById("roadmap").offsetTop;

      if (scroll >= roadmapTop) {
        this.currentIndex = 4;
      } else if (scroll >= aboutTop) {
        this.currentIndex = 3;
      } else if (scroll >= characterTop) {
        this.currentIndex = 2;
      } else if (scroll >= storyTop) {
        this.currentIndex = 1;
      } else {
        this.currentIndex = 0;
      }

      if (scroll >= 50) {
        this.isShowTopbarScrollBackground = true;
      } else {
        this.isShowTopbarScrollBackground = false;
      }
    },
    // comming soon
    comming() {
      if (isPhone()) {
        this.$toast({
          className: "toastStyle",
          icon: "star",
          type: "text",
          message: "COMING SOON",
          duration: 2000,
          closeOnClick: true,
          closeOnClickOverlay: true,
        });
      } else {
        this.$message({
          customClass: "msgStyle",
          iconClass: "el-icon-star-on",
          type: "warning",
          message: "COMING SOON",
          duration: 2000,
        });
      }
    },

    // ========== goto ==========
    gotoPage(pageType) {
      switch (pageType) {
        case "Twitter":
          window.open("https://twitter.com/AotuNFT", "_blank");
          break;
        case "Discord":
          window.open("https://discord.gg/HsTUBMZuc6", "_blank");
          break;
        case "Email":
          // window.location.href = "aotunft@gmail.com";
          // window.open("https://aotunft@gmail.com", "_blank");
          break;
        case "QA":
          window.open("https://dior-bob.gitbook.io/aotuworld-1", "_blank");
          break;
        default:
          break;
      }
    },
  },
  mounted() {
    // this.initialize();
    window.addEventListener("scroll", this.handleScroll, {
      passive: true,
    });
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.handleScroll, {
      passive: true,
    });
  },
};
</script>

<style lang="less" scoped>
.top-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  background: linear-gradient(
    180deg,
    rgba(0, 0, 0, 0.5) 0%,
    rgba(0, 0, 0, 0) 100%
  );
  transition: all 0.2s ease-out;
  z-index: 9;

  .mobile {
    display: none;
  }

  // topbar center wrapper
  .center-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 1258px;
    height: 100%;
    margin: 0 auto;
  }

  // topbar left
  .t-b-left {
    ul,
    li {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    ul {
      display: flex;
      align-items: center;
      width: 100%;
      height: 100%;
    }
    li {
      margin-left: 40px;
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #ffffff;
      line-height: 16px;
      cursor: pointer;
      transition: color 0.2s ease;
    }
    li:first-child {
      margin: 0;
      cursor: default;
    }
    .logo {
      width: 120px;
    }

    .active-li {
      color: #edaf33;
    }
  }

  // topbar right
  .t-b-right {
    display: flex;
    .right-icon {
      width: 30px;
      margin-left: 28px;
      cursor: pointer;
    }

    span {
    }
  }
}
.top-bar-scroll-background {
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(30px);
}

@media screen and (max-width: 768px) {
  .top-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 16vw;
    background: #222222;
    z-index: 9;

    // topbar center wrapper
    .center-wrapper {
      display: none;
    }

    .mobile {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .t-b-left {
        margin-left: 4vw;

        .logo {
          width: 32vw;
        }
      }

      .t-b-right {
        margin-right: 6.6667vw;
        .right-icon {
          margin: 0;
        }
        .right-icon:nth-child(1) {
          width: 6.1333vw;
          margin-right: 6.6667vw;
        }
        .right-icon:nth-child(2) {
          width: 6.4vw;
          margin-right: 6.6667vw;
        }
        .right-icon:nth-child(3) {
          width: 5.0667vw;
        }
      }
    }
  }
}
</style>
